package com.help.common.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.help.domain.User;;

import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 风亦未止
 * @date 2021/11/20 19:31
 */
public class JwtUtil {
    private static String sign="$zhieasy$";

    /**
     * 生成token，用户
     * @param user
     * @return
     */
    public static String getToken(User user){
        HashMap<String,Object> data=new HashMap<>();
        data.put("openid",user.getOpenid());
        data.put("nickName",user.getNickName());
        data.put("avatarUrl",user.getAvatarUrl());
        Calendar instance = Calendar.getInstance();
        //7天过期
        instance.add(Calendar.DATE,7);
        String token = JWT.create()
                .withClaim("user",data)
                .sign(Algorithm.HMAC256(JwtUtil.sign));
        return token;
    }

    /**
     * 验证token
     * @param token
     * @return
     */
    public static DecodedJWT verify(String token){
        return JWT.require(Algorithm.HMAC256(JwtUtil.sign)).build().verify(token);
    }

    public static Map<String,Object> getUserMap(String token){
        DecodedJWT decode = JwtUtil.verify(token);
        Map<String,Object> user = decode.getClaim("user").asMap();
        return user;
    }

    public static String getNickName(String token){
        Map<String, Object> userMap = getUserMap(token);
        return (String) userMap.get("nickName");
    }

    public static String getOpenid(String token){
        Map<String, Object> userMap = getUserMap(token);
        return (String) userMap.get("openid");
    }

    public static String getAvatarUrl(String token){
        Map<String, Object> userMap = getUserMap(token);
        return (String) userMap.get("avatarUrl");
    }

}
